# -*- coding: utf-8 -*-
import os
from abc import ABC
from app.models import db_session
from app.views import CommonHandler
from app.models.model import MetaModel
from app.models.cod import ValkyrjaException, Error, named
from app.models.dao import db2meta, clear
from app.configs import tmp_path


class MetaHandler(CommonHandler, ABC):
    async def get(self):
        mine_code = self.get_argument("mine_code", None)
        metas = db_session().query(MetaModel).filter(MetaModel.mine_code == mine_code).all()
        await self.respose(data=[meta.dxf() for meta in metas])

    async def post(self):
        params, cont = self.json_params(), {}

        code, name, sign = params['code'], params['name'], params['sign']
        type, piece = params['type'], params['piece']
        no, size = params['no'], params['size']

        query = db_session().query(MetaModel).filter(
            MetaModel.mine_code == code,
            MetaModel.name.like('%'+name+'%'),
            MetaModel.sign.like('%'+sign+'%'),
            MetaModel.type.like('%'+type+'%'),
            MetaModel.piece.like('%'+piece+'%')
        ).order_by(MetaModel.create_time.desc())

        cont['total'] = query.count()
        metas = query.limit(size).offset((no - 1) * size)
        cont['data'] = [meta.dxf() for meta in metas]

        await self.respose(data=cont)

    async def put(self):
        params, session = self.json_params(), db_session()

        metas = session.query(MetaModel).filter(
            MetaModel.meta_id == params['meta_id']
        ).all()
        if len(metas) == 0:
            await self.respose(error=Error.NotMeta)
            return

        meta = metas[0]
        name = named(meta.mine_code, meta.sign, meta.type, meta.piece, meta.meta_id)
        old_file = tmp_path + name + ".dxf"

        meta.name, meta.sign = params['name'], params['sign']
        meta.type, meta.piece = params['type'], params['piece']
        meta.major_ver = params['version']
        if meta.major_ver != params['version']:
            meta.minor_ver = 1

        name = named(meta.mine_code, meta.sign, meta.type, meta.piece, meta.meta_id)
        new_file = tmp_path + name + ".dxf"

        if os.path.exists(old_file):
            os.renames(old_file, new_file)

        session.commit()

        await self.respose()

    async def delete(self):
        params = self.json_params()

        # 检测meta数据是否存在
        try:
            meta = db2meta(params['meta_id'])
        except ValkyrjaException:
            await self.respose(error=Error.NotMeta)
            return

        # 清除meta_id的所有数据表内容
        clear(params['meta_id'])

        # 拼接存储文件规则
        code, meta_id = meta['mine_code'], meta['meta_id']
        sign, type, piece = meta['sign'], meta['type'], meta['piece']
        name = named(code, sign, type, piece, meta_id)

        # 如果dxf文件存在删除
        dxf = tmp_path + name + '.dxf'
        if os.path.exists(dxf):
            os.remove(dxf)

        # 如果dwg文件存在删除
        dwg = tmp_path + name + '.dwg'
        if os.path.exists(dwg):
            os.remove(dwg)

        await self.respose()
